﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HonStats.Heartbeat.Model;
using HonStats.Heartbeat.Library;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;

namespace HonStats.Heartbeat
{

    public class Scraper
    {
        public static volatile bool Running;
        private Thread SpawnThread;
        private int MaxUserID { get; set; }
        private int MaxThreads { get; set; }
        private int IDsToFetch;
        private static int CurrentUserID;
        private Parser StatsParser = new Parser();

        /// <summary>
        /// Default Scraper settings if none are provided
        /// </summary>
        public Scraper()
            : this(0, Int32.MaxValue, 25, 10)
        {
        }
        
        public Scraper(int currentUserID, int MaxUserID, int MaxThreads, int idsToFetch)
        {
            CurrentUserID = currentUserID;
            this.MaxUserID = MaxUserID;
            this.MaxThreads = MaxThreads;
            this.IDsToFetch = idsToFetch;
            Running = false;
            //ThreadPool.SetMaxThreads(MaxThreads, MaxThreads);
        }

        public void Start()
        {
            if (!Running)
            {
                Running = true;
                SpawnThread = new Thread(SpawnThreads);
                SpawnThread.Start();
            }
        }

        public void Stop()
        {
            if (Running == true)
            {
                Running = false;
                SpawnThread.Join();
            }
        }

        private void SpawnThreads()
        {
            //int availableWorkerThreads;
            //int availableCompletionThreads;
            //int maxWorkerThreads;
            //int maxCompletionThreads;

            //while (Running)
            //{

                    //ThreadPool.GetAvailableThreads(out availableWorkerThreads, out availableCompletionThreads);
                    //ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionThreads);
                    //while ((maxWorkerThreads - availableWorkerThreads) < 10)
                    for (int i = 0; i < MaxUserID; i++) //will stop at MaxUserID unless fetching more then 1 id at a time
                    {
                        //Console.WriteLine("Used: {0}", maxWorkerThreads - availableWorkerThreads);
                        ThreadPool.QueueUserWorkItem(new WaitCallback(FetchNextStats));
                        Thread.Sleep(10);
                        //ThreadPool.GetAvailableThreads(out availableWorkerThreads, out availableCompletionThreads);
                    }
                    Thread.Sleep(10);
            //}

        }

        public void FetchNextStats(object state)
        {
            for (int i = 0; i < 1 ; i++)
            {
                string temp = "";
                for (int index = 0; index <= IDsToFetch; index++ ) // used to put together a 100 account Request (works) IDsToFetch must be 1 to stop properly
                {
                    int currentUserID = Interlocked.Increment(ref CurrentUserID);
                    temp = temp + string.Format("&account_id[{0}]={1}", index, currentUserID);
                    index++;
                    //Console.WriteLine("Fetching UserID: {0}", currentUserID);
                }

                string userData = FetchStats(temp);
                var User = Parser.Parse(userData);

                for (int x = 0; x < User.Count; x++) // Loop through List with for
                {
                    Console.WriteLine(User[x].account_id + " - " + User[x].nickname);
                }

                
            }
        }

        // commented out to make use of the multiple account request
        //public static string FetchStats(string Nick)
        //{
        //    var rawUserID = GetUrlContents(String.Format("https://masterserver.hon.s2games.com/client_requester.php?f=nick2id&nickname[0]={0}", Nick));
           
        //    var serializer = new PHPSerializer();
        //    Hashtable deserializedUserInfo = (Hashtable)serializer.Deserialize(rawUserID);//Deserialize the Hashtable
            
        //    var UserID = deserializedUserInfo[Nick].ToString();
        //    return FetchStats(UserID);
        //}

        
        public static string FetchStats(string UserID) // changed from INT to string for the multi account request
        {
            return GetUrlContents("https://masterserver.hon.s2games.com/client_requester.php?f=get_all_stats" + UserID);
        }


        public static string GetUrlContents(string Url)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(Url);
            webRequest.Method = "GET";

            var response = webRequest.GetResponse();

            string result;
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                result = sr.ReadToEnd();
            }

            return result;

        }
 

    }
}
